import re

from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from apps.users.models import UserInfo, Goods


class RegisterSerializer(ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ["student_id", "user_name", "password", "school_zone", "profile", "qq"]
        extra_kwargs = {
            "student_id": {"required": True},
            "user_name": {"required": True},
            "password": {"required": True},
            "school_zone": {"required": True},
            "qq": {"required": True}
        }

    def validate_student_id(self, value):
        pattern = re.compile(r"^\d+$")
        if pattern.match(value):
            return value
        else:
            raise serializers.ValidationError("学号格式不正确")

    def validate_password(self, value):
        # 密码最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符
        pattern = re.compile(r"^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[~!@#$%^&*? ]).*$"r"")
        if pattern.match(value):
            return value
        else:
            raise serializers.ValidationError("密码最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符(~!@#$%^&*? )")

    def validate_school_zone(self, value):
        if 0 > value or value > len(UserInfo.SCHOOL_ZONE):
            raise serializers.ValidationError("选项不合法")
        return value

    def validate_qq(self, value):
        pattern = re.compile(r"^[1-9][0-9]{4,}$")
        if pattern.match(value):
            return value
        else:
            raise serializers.ValidationError("qq格式不正确")


class UserInfoSerializer(ModelSerializer):
    txn_statistics = serializers.SerializerMethodField()
    commuca_statistics = serializers.SerializerMethodField()
    avatar = serializers.CharField(source="avatar.photo_url")
    school_zone = serializers.CharField(source="get_school_zone_display")

    class Meta:
        model = UserInfo
        fields = ["id", "student_id", "user_name", "avatar", "school_zone", "profile", "qq", "txn_statistics",
                  "commuca_statistics"]

    def get_txn_statistics(self, row):
        result = dict()
        result["sold_goods"] = row.goods_seller_set.all().count()  # 售卖量
        result["purchase_goods"] = row.goods_wanted_person_set.count()  # 购买量
        result["current_goods"] = row.goods_seller_set.all().count()  # 当前上架数量
        result["success_transaction"] = row.goods_seller_set.filter(goods_is_sold=True).count()  # 成功交易量
        return result

    def get_commuca_statistics(self, row):
        result = dict()
        result["focus_topics"] = row.thread_appreciate_peoples_set.all().count()  # 关注帖子数量
        result["launch_topics"] = row.thread_author_info_set.all().count()  # 发表帖子数量
        return result


class GoodSerializer(ModelSerializer):
    seller = serializers.SerializerMethodField()
    goodsInfo = serializers.SerializerMethodField()

    class Meta:
        model = Goods
        fields = ["seller", "goodsInfo"]

    def get_seller(self, row):
        result = dict()
        result["id"] = row.seller.id
        result["user_name"] = row.seller.user_name
        result["school_zone"] = row.seller.get_school_zone_display()
        result["avatar"] = row.seller.avatar.photo_url()
        result["qq"] = row.seller.qq
        return result

    def get_goodsInfo(self, row):
        result = dict()
        result["goods_id"] = row.id
        result["goods_main_image"] = row.goods_main_image
        # 拿到商品图片
        images = row.goodsallimage_set.all()
        result["goods_img"] = list()
        for img in images:
            result["goods_img"].append(img.image_path)
        result["goods_title"] = row.goods_title
        result["goods_price"] = row.goods_price
        # 拿到商品标签
        tags = row.goods_tags.all()
        result["goods_tags"] = list()
        for tag in tags:
            result["goods_tags"].append(tag.tags_content)
        result["goods_desc"] = row.goods_desc
        result["goods_launch_time"] = row.goods_launch_time
        result["goods_is_sold"] = row.goods_is_sold
        # 拿到商品想要人的数量
        result["goods_wanted_person"] = row.goods_wanted_person.all().count()
        return result

class WantedUserSerializer(ModelSerializer):

    users = serializers.SerializerMethodField()

    def get_users(self, row):
        wanted_users = row.goods_wanted_person.all()
        return [{
            "id": user.id,
            "student_id": user.student_id,
            "user_name": user.user_name,
            "avatar": user.avatar,
        } for user in wanted_users]

    class Meta:
        model = Goods
        fields = ["users"]
